package com.foreknow.controller;

import com.foreknow.model.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GetMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置服务器端向客户端响应的内容的类型(MIME) https://www.runoob.com/http/mime-types.html
        resp.setContentType("text/html;charset=utf-8");
        //获取输出流主要用于向网页中显示信息
        PrintWriter out = resp.getWriter();
        //获取请求参数
        String name = req.getParameter("username");
        String pass = req.getParameter("password");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //调用Service中的方法
        GuestbookService service = new GuestbookServiceImpl();
        Guestbook gb = new Guestbook();
        gb.setName(name);
        gb.setPass(pass);
        gb.setPhone(phone);
        gb.setEmail(email);
        gb.setTitle(title);
        gb.setContent(content);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        gb.setCreatedtime(simpleDateFormat.format(new Date()));

        boolean isRight = service.register(gb);
        if(isRight) {
            //            out.println("<a href='getQueryAll'>get query all</a>");
            //请求转发
            //req.getRequestDispatcher("getQueryAll").forward(req,resp);
            //重定向
            resp.sendRedirect("getQueryAll");
        }else {
            out.println("add error......");
        }
    }
}
